const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const cors = require('koa2-cors')

const logger = require('./utils/log4js').api

require('./utils/mongodb')

// init application database
const User = require('./models/user')
const query = User.find()
query.exec(function (err, res) {
  if (err) logger.error(err)
  if (!res.length) {
    var user = new User({ name: 'admin', pass: 'admin' })
    user.save()
  }
})

const index = require('./routes/index')
const users = require('./routes/users')
const musics = require('./routes/musics')
const token = require('./routes/token')
const qiniu = require('./routes/qiniu')
const notes = require('./routes/notes')

// error handler
onerror(app)

// defult error handler
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    ctx.status = err.status || err.code
    ctx.body = {
      success: false,
      message: err.message
    }
  }
})

// cors
app.use(cors())

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  logger.info(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(musics.routes(), musics.allowedMethods())
app.use(token.routes(), token.allowedMethods())
app.use(qiniu.routes(), qiniu.allowedMethods())
app.use(notes.routes(), notes.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
